using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;

[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour, InputSystem_Actions.IPlayerActions
{
    

    [SerializeField] private float moveSpeed;


    private InputSystem_Actions input;
    private Rigidbody rb;
    
    private Vector2 currentMoveDirection;
    private Vector2 lastMoveDirection;

    public Vector3 forward { get; private set; }

    private Player player;
    
    private bool isMove;
    
    private void Awake()
    {
        input = new InputSystem_Actions();
    }

    private void Start()
    {
        player = GetComponent<Player>();
        rb = GetComponent<Rigidbody>();
    }

    private void OnEnable()
    {
        input.Player.SetCallbacks(this);
        input.Player.Enable();
    }

    private void OnDisable()
    {
        input.Player.Disable();
    }
    

    void Update()
    {
        
    }

    private void FixedUpdate()
    {
        if (isMove)
        {
            AddMovement();
        }
    }

    public void OnMove(InputAction.CallbackContext context)
    {
        if (context.phase == InputActionPhase.Performed)
        {
            currentMoveDirection = context.ReadValue<Vector2>();
            isMove = true;
            return;
        }

        if (context.phase == InputActionPhase.Canceled)
        {
            isMove = false;
            lastMoveDirection = currentMoveDirection;
            currentMoveDirection = Vector2.zero;
            StopMovement();
        }
    }


    private void AddMovement()
    {
        Vector3 direction = new Vector3(currentMoveDirection.x, 0, currentMoveDirection.y);
        rb.linearVelocity = direction.normalized * moveSpeed;
    }

    private void StopMovement()
    {
        rb.linearVelocity = Vector3.zero;
    }
}
